<template>
<div>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    width="100%"
    :fullscreen="true"
    top="0"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="checkNeedDoubleCheck()" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户名" prop="userName">
            <el-input v-model="dataForm.userName" maxlength="30" placeholder="登录帐号(可以是纯数字、纯字母或数字、字母及其他符号组合)"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户姓名" prop="realName">
          <el-input v-model="dataForm.realName" placeholder="用户姓名"></el-input>
        </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="身份证号码" prop="idcode">
            <el-input v-model="dataForm.idcode" placeholder="身份证号码" maxlength="18"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门名称" prop="depart">
            <el-input v-model="dataForm.depart" placeholder="部门名称"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      



      
      <el-row>
        <el-col :span="12">
              <el-form-item label="所属机构" 
                     :class="{ 'is-required': userorgid }"
               prop="orgid">

                <el-select
                    v-model="dataForm.orgid"
                    clearable
                    filterable
                    style="width:100%"
                    remote
                
                    placeholder="输入机构代码或名称"
                    :remote-method="remoteMethod"
                    :loading="loading">
                    <el-option
                      v-for="item in list"
                      :key="item.branchid"
                      :label="item.branchname"
                      :value="item.branchid">
                    </el-option>
                  </el-select>


              <div class="contentpanel-layout" v-if="false">
                <div class="contentview-layout bottom-in">
                  <div class="contentview-main" style="padding: 0px 0px 0px 0px;">
                    <div class="search-box" style="width:100%;">
                      <el-popover placement="bottom-start" :width="width" v-model="visible2" trigger="manual">
                        
                        <div slot="reference">
                            <el-input v-model="value" placeholder="输入机构代码或名称" 
                             @keyup.native="handleFocus"
                             @blur="handleBlur" style="width:100%"></el-input>

                        </div> 
                        
                        <el-table :data="list" :height="height" @row-click="onClickItem" @row-dblclick="onClickItem">
                          <el-table-column property="branchid" label="机构代码"></el-table-column>
                          <el-table-column property="branchname" label="机构名称"></el-table-column>
                        </el-table>
                             
                      </el-popover>
                    </div>    
                  </div>
                </div> 
              </div>


              </el-form-item>
        </el-col>
        

        <el-col :span="12">
          <el-form-item label="状态" size="mini" prop="status">
            <el-radio-group v-model="dataForm.status">
              <el-radio :label="0">禁用</el-radio>
              <el-radio :label="1">正常</el-radio>
            </el-radio-group>
          </el-form-item>
         </el-col>
      </el-row>


      <el-row>
        <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                <el-input v-model="dataForm.email" placeholder="邮箱"></el-input>
              </el-form-item>
        </el-col>
        <el-col :span="12">
                <el-form-item label="联系方式" prop="mobile">
                  <el-input v-model="dataForm.mobile" placeholder="固话(xxxx-xxxxxxxx)或11位手机号"></el-input>
                </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="操作范围" prop="enableflag">

            <el-select v-model="dataForm.enableflag" placeholder="操作范围" style="width:100%">
                <el-option
                  v-for="item in dataForm.operateRangeList"
                  :key="item.value"
                  :label="item.text"
                  :value="item.value">
                </el-option>
            </el-select>

          </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="dataForm.remark" placeholder="备注"></el-input>
            </el-form-item>
        </el-col>
      </el-row>
      
      <el-row>
        <el-col :span="80">
            <el-form-item label="角色" size="mini" prop="roleIdList">
              <el-checkbox-group v-model="dataForm.roleIdList">
                <el-checkbox border   v-for="role in roleList" :key="role.roleId" :label="role.roleId">{{ role.roleName }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
        </el-col>

      </el-row>


    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="checkNeedDoubleCheck()">确定</el-button>
    </span>
  </el-dialog>

  <double-check v-if="doubleCheckVisible" ref="doubleCheck"  @refreshDataList="dataFormSubmit" ></double-check>

  </div>


</template>

<script>
  import { isEmail, isMobile, isPhone } from '@/utils/validate'
  import DoubleCheck from './double-check'
  export default {
    data () {

      var validateEmail = (rule, value, callback) => {
        if (!isEmail(value)) {
          callback(new Error('邮箱格式错误'))
        } else {
          callback()
        }
      }

      var validatePhone = (rule, value, callback) => {
        if (!isMobile(value) && !isPhone(value)) {
          callback(new Error('联系方式格式错误'))
        } else {
          callback()
        }
      }

      var validateOrgid = (rule, value, callback) => {
        if (this.userorgid && !value) {
          callback(new Error('所属机构不能为空'))
        } else {
          callback()
        }
      }

      return {
        visible: false,
        visible2: false,
        loading: false,
        value: '',
        value2: '',
        width:660,
        height:270,
        doubleCheckVisible: false,
        needDoubleCheck: false,
        list:[

            ],

        roleList: [],
        dataForm: {
          id: 0,
          userName: '',
          realName: '',
          salt: '',
          email: '',
          mobile: '',
          roleIdList: [],
          status: 1,
          idcode: '',
          depart: '',
          enableflag: '',
          remark: '',
          operateRangeList: [],
          orgid: ''
        },
        dataRule: {
          userName: [
            { required: true, message: '用户名不能为空', trigger: 'blur' }
          ],
          realName: [
            { required: true, message: '用户姓名不能为空', trigger: 'blur' }
          ],
          orgid:[
            { validator: validateOrgid, trigger: 'blur' }
          ],

          email: [
            { required: true, message: '邮箱不能为空', trigger: 'blur' },
            { validator: validateEmail, trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '联系方式不能为空', trigger: 'blur' },
            { validator: validatePhone, trigger: 'blur' }
          ],
          depart: [
            { required: true, message: '部门名称不能为空', trigger: 'blur' }
          ],
          enableflag: [
            { required: true, message: '操作范围不能为空', trigger: 'blur' }
          ],
          roleIdList:[
            { required: true, message: '角色不能为空', trigger: 'blur' }
          ]
        }
      }
    },

    computed: {
      userorgid: {
        get () { return this.$store.state.user.orgid }
      }
    },

    components: {
      DoubleCheck
    },

    methods: {
      remoteMethod(query) {
        // if (query !== '') {
          this.loading = true;

          this.$http({
            url: this.$http.adornUrl(`/sys/user/branch/search`),
            method: 'get',
            params: this.$http.adornParams({
              "key": query || ''
            })
          }).then(({data}) => {
            this.loading = false;
            if (data && data.code === 0) {
                this.list = data.list;
            }
          })     
          
        // } else {
        //   this.list = [];
        // }
      },
      init (id) {
        this.value = "";
        this.value2 = "";
        this.dataForm.id = id || 0

        this.remoteMethod()

        this.$http({
          url: this.$http.adornUrl(`/sys/user/item/list`),
              method: 'get',
              params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.operateRangeList = data.operateRangeList
              this.needDoubleCheck = data.needDoubleCheck;
            }
        })

        this.$http({
          url: this.$http.adornUrl('/sys/role/select'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          this.roleList = data && data.code === 0 ? data.list : []
        }).then(() => {
          this.visible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()
          })
        }).then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/sys/user/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                var username = data.user.username;
                if (data.user.orgid){
                  username = username.split("#")[0];
                }
                this.dataForm.userName = username
                this.dataForm.salt = data.user.salt
                this.dataForm.email = data.user.email
                this.dataForm.mobile = data.user.mobile
                this.dataForm.roleIdList = data.user.roleIdList
                this.dataForm.status = data.user.status
                this.dataForm.realName = data.user.realName
                this.value2 = data.user.orgid
                this.value = data.user.orgid
                this.dataForm.orgid = data.user.orgid

                this.dataForm.idcode = data.user.idcode
                this.dataForm.depart = data.user.depart
                this.dataForm.enableflag = data.user.enableflag
                this.dataForm.remark = data.user.remark

              }
            })
          }
        })
      },

    handleFocus(){
      console.log("handleFocus:" + this.value)
      this.$http({
              url: this.$http.adornUrl(`/sys/user/branch/search`),
              method: 'get',
              params: this.$http.adornParams({
                "key":this.value
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                  this.list = data.list;
                  this.visible2 = true;
              }
            })

    },
    handleBlur(){
      this.visible2 = false;
    },
    onClickItem(row){
      this.value = row.branchname;
      this.value2 = row.branchid;
      this.visible2 = false;
    },

      checkNeedDoubleCheck(){
        if (this.needDoubleCheck){
          this.$refs['dataForm'].validate((valid) => {
              if (valid) {
                this.doubleCheckVisible = true;
                this.$nextTick(() => {
                  this.$refs.doubleCheck.init()
                })
              }
          })
        }else{
          this.dataFormSubmit ();
        }
      },


      // 表单提交
      dataFormSubmit (username, passwd, callback) {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            // if (!this.value2){
            //   this.$message.error("机构不能为空");
            //   return;
            // }



            this.$http({
              url: this.$http.adornUrl(`/sys/user/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'userId': this.dataForm.id || undefined,
                'username': this.dataForm.userName,
                'realName': this.dataForm.realName,
                'password': this.dataForm.password,
                'salt': this.dataForm.salt,
                'email': this.dataForm.email,
                'mobile': this.dataForm.mobile,
                'status': this.dataForm.status,
                'roleIdList': this.dataForm.roleIdList,
                'orgid': this.dataForm.orgid,

                'idcode': this.dataForm.idcode,
                'depart': this.dataForm.depart,
                'enableflag': this.dataForm.enableflag,
                'remark': this.dataForm.remark,
                'doubleCheck': {
                  'username': username,
                  'passwd': passwd
                }
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: !this.dataForm.id ? '操作成功,初始密码：'+ data.defaultPwd : '操作成功',
                  type: 'success',
                  duration: 2000,
                  onClose: () => {
                    this.visible = false
                    if (callback){
                      callback();
                    }
                   
                    this.$emit('refreshDataList')
                  }
                });
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
<style>
.el-checkbox+.el-checkbox {
margin-left: 0px;
}

.el-checkbox.is-bordered+.el-checkbox.is-bordered {
    margin-left: 0px;
}
.el-checkbox {
margin-right: 25px;
width: 150px !important;
}

</style>